package cn.hbads.support.json.support;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.fasterxml.jackson.databind.node.NumericNode;
import com.fasterxml.jackson.databind.node.TextNode;

import java.util.Comparator;

/**
 * @author : yvvb
 * @className : JsonNodeComparator
 * @date : 2025/4/17
 * @apiNote 扩展数值类型以及空字符串和空的比对
 */
public enum JsonNodeComparator implements Comparator<JsonNode> {
    INSTANCE;

    @Override
    public int compare(JsonNode o1, JsonNode o2) {
        if (o1.equals(o2)) {
            return 0;
        }
        if ((o1 instanceof NumericNode) && (o2 instanceof NumericNode)) {
            Double d1 = o1.asDouble();
            Double d2 = o2.asDouble();
            if (d1.compareTo(d2) == 0) {
                return 0;
            }
        }
        if ((o1.getNodeType() == JsonNodeType.NULL) && (o2 instanceof TextNode && "".equals(o2.asText()))) {
            return 0;
        }
        if ((o2.getNodeType() == JsonNodeType.NULL) && (o1 instanceof TextNode && "".equals(o1.asText()))) {
            return 0;
        }
        return 1;
    }
}
